package cn.tedu.fruitshop.ex.handler;


import cn.tedu.fruitshop.ex.ServiceException;
import cn.tedu.fruitshop.web.JsonResult;
import cn.tedu.fruitshop.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
//@RestControllerAdvice 添加了此注解的类中的特定方法将作用于整个项目任何处理请求的方法的过程
public class GrobalExceptionHandler {

    public GrobalExceptionHandler() {
        log.debug("创建全局异常处理器对象:GrobalExceptionHandler");
    }

    @ExceptionHandler
    public JsonResult handlerServiceExceptin(ServiceException e){
        log.debug("处理请求的方法抛出了ServiceException,将统一进行处理");
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
        log.debug("开始处理BindException");

        String defaultMessage = e.getFieldError().getDefaultMessage();

        /*StringJoiner stringJoiner = new StringJoiner(",","请求参数格式错误","!!!");
        List<FieldError> fileErrors = e.getFieldErrors();
        for (FieldError fieldError : fileErrors){
            String defaultMessage = fieldError.getDefaultMessage();
            stringJoiner.add(defaultMessage);
        }*/

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,defaultMessage);
    }

    @ExceptionHandler
    public JsonResult<Void> handleConstrainViolationException(ConstraintViolationException e){
        log.debug("开始处理ConstraintViolationException");
        StringJoiner stringJoiner = new StringJoiner(",");
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> c: constraintViolations) {
            stringJoiner.add(c.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,stringJoiner.toString());
    }



}
